<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{

    // 分页时新增导致重复查出数据
    public function index(Request $request)
    {
        $page = (int) $request->query('page', 1);
        $limit = (int) $request->query('limit', 3);

        $lastMinTime = $request->query('last_min_time', '');

        $query = User::query();

        $total = $query->count();

        if ($total === 0) {
            abort(404);
        }

        $maxPage = ceil($total / $limit);

        if ($page > $maxPage) {
            abort(404);
        }

        $data = $query->forPage($page, $limit)
            ->latest()
            ->get()
            ->toArray();

        if (!empty($lastMinTime)) {

            $temp = [];
            $add = 0;
            foreach ($data as $datum) {
                if ($datum['created_at'] < $lastMinTime) {
                    $temp[] = $datum;
                } else {
                    $add++;
                }
            }

            $total -= $add;

            $maxPage = ceil($total / $limit);

            if (empty($temp)) {
                abort(404);
            }
        }

        if (empty($data)) {
            abort(404);
        }

        return [
            'data' => !empty($lastMinTime) ? $temp : $data,
            'pagination' => [
                'limit' => $limit,
                'page' => $page,
                'total_page' => $maxPage,
                'total' => $total,
            ],
        ];
    }

    public function create(Request $request)
    {
        $body = $request->post();

        $user = new User();

        $user->name = $body['name'];
        $user->email = $body['email'];
        $user->email_verified_at = date('Y-m-d H:i:s');
        $user->password = Hash::make($body['password']);
        $user->avatar = $body['avatar'] ?? '';
        $user->remember_token = $body['remember_token'] ?? '';
        $user->introduction = $body['introduction'] ?? '';

        $user->save();

        return $user;
    }
}
